module Animation
  def initialize
    super
    @frame_duration ||= 100
  end
  
  def animate
    return unless animating?
    @last_frame_time ||= now
    while @frame_duration.since? @last_frame_time
      @last_frame_time += @frame_duration
      if animation_finished?
        play_next_animation
      else
        @frame = (@frame + 1) % @animations[@animation].length
      end
    end
  end
  
  def animation_finished?
    if @force_animation_until and !@force_animation_until.yet?
      return false
    elsif !animating? or @frame >= @animations[@animation].length - 1
      return true
    end
    return false
  end
  
  def animating?
    !@animation.nil?
  end
  
  def current_image
    if animating?
      @frames[@animations[@animation][@frame]] if animating?
    else
      @frames[0]
    end
  end
  
  def draw
    animate
    y = @pos.y - @pos.z
    current_image.draw_rot @pos.x.round, @pos.y.round, z_order, 0, 0.5, 1
  end
  
  def play_animation(animation, options={})
    animation = "#{animation}_#{@direction}" if @direction
    animation = animation.to_sym if animation.is_a? String
    return if @animation == animation or !@animations.include? animation
    return if @force_animation_until and !@force_animation_until.yet?
    @animation = animation
    @next_animation = options[:then]
    @force_animation_until = now + options[:for].ms
    @frame = 0
  end
  
  def play_next_animation
    if @next_animation
      play_animation @next_animation
    end
    @frame = 0
  end
end
